package com.ldk.framework.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ldk.base.framework.dao.IBaseDAO;
import com.ldk.base.framework.service.impl.BaseService;
import com.ldk.base.framework.util.SystemUtil;
import com.ldk.framework.service.IPhoneValidcodeService;
import com.ldk.framework.dao.IPhoneValidcodeDAO;
import com.ldk.framework.entity.PhoneValidcode;

/**
* PhoneValidcodeService接口实现类
* @author xiangwl
*/
@Service
public class PhoneValidcodeService extends BaseService<PhoneValidcode> implements IPhoneValidcodeService {

	@Autowired
	private IPhoneValidcodeDAO phoneValidcodeDAO;

	@Override
	protected IBaseDAO<PhoneValidcode> getBaseDao() {
     	return this.phoneValidcodeDAO;
	}
	@Override
	public Boolean checkInputCorrect(String dbKey, String phoneNo,
			String validCode) {
		PhoneValidcode query = new PhoneValidcode();
		query.setPhoneNo(phoneNo);
		query.setValidCode(validCode);
		
		PhoneValidcode model = selectOne(dbKey, query);
		
		return model != null;
	}
	
	@Override
	public Boolean checkExpired(String dbKey, String phoneNo) {
		PhoneValidcode query = new PhoneValidcode();
		query.setPhoneNo(phoneNo);
		PhoneValidcode model = selectByKey(dbKey, query);
		//如果不存在或已过期则返回过期状态重新获取验证码操作
		if (model == null || model.getIsExpired() == null || model.getIsExpired())
			return true;
		int smsTimeout = 15;//过期单位分钟
		long currentTime = SystemUtil.getAllSeconds();
		long sendTime = model.getSendTime() == null ? 0 : model.getSendTime();
		if(currentTime - sendTime > (smsTimeout * 60)){
			validCodeExpired(dbKey, phoneNo);
			return true;
		}
		return false;
	}
	
	@Override
	public Boolean checkExpired(String dbKey, String phoneNo, String validCode) {
		Boolean isExpired = checkExpired(dbKey, phoneNo);
		if(isExpired) return true;
		
		PhoneValidcode query = new PhoneValidcode();
		query.setPhoneNo(phoneNo);
		query.setValidCode(validCode);
		query.setIsExpired(false);
		
		PhoneValidcode model = selectOne(dbKey, query);
		if(model == null) return true;
		return false;
	}
	@Override
	public Boolean scheduleExpired(String dbKey) {
		int smsTimeout = 15;//过期单位分钟
		//转换为秒
		smsTimeout = smsTimeout * 60;
		
		return phoneValidcodeDAO.scheduleExpired(dbKey, smsTimeout);
	}
	@Override
	public Boolean validCodeExpired(String dbKey, String phoneNo) {
		//修改短信过期
		PhoneValidcode phoneValidCode = new PhoneValidcode();
		phoneValidCode.setPhoneNo(phoneNo);
		phoneValidCode.setIsExpired(true);
		updateByKey(dbKey, phoneValidCode);
		return true;
	}
}
